package middleware

import (
	"context"
	"net/http"
	"server/utils"

	tojson "gitee.com/ruikc/tojson"

	"github.com/zeromicro/go-zero/rest/httpx"
)

type UserMiddleware struct {
}

func NewUserMiddleware() *UserMiddleware {
	return &UserMiddleware{}
}

func (m *UserMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		AccessToken := r.Header.Get("Authorization")
		if AccessToken == "" {
			httpx.OkJsonCtx(r.Context(), w, tojson.NoAuth())
			return
		}
		value, _ := utils.Rds.Get("todo-token:" + AccessToken)
		if value == "" {
			httpx.OkJsonCtx(r.Context(), w, tojson.NoAuth())
			return
		}
		jwtUser := &utils.JwtUser{}
		utils.JsonToStruct(value, jwtUser)
		reqCtx := r.Context()
		ctx := context.WithValue(reqCtx, utils.JwtUserKey, jwtUser)
		newReq := r.WithContext(ctx)
		next(w, newReq)
	}
}
